package com.party.controller.sys.learning;

import com.party.common.Page;
import com.party.common.Tools;
import com.party.model.Curriculum;
import com.party.model.Curriculum2Content;
import com.party.model.LearningContent;
import com.party.model.SysUser;
import com.party.service.study.Curriculum2contentService;
import com.party.service.study.CurriculumService;
import com.party.service.study.LearningContentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 011926 on 2014/9/14.
 */
@Controller
@RequestMapping("/sys/content")
public class ContentController
{
    @Resource
    CurriculumService curriculumService;
    @Resource
    LearningContentService learningContentService;
    @Resource
    Curriculum2contentService curriculum2contentService;
    private int pageSize = 9;

    /**
     *  列表
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index(
            HttpServletRequest request,
            HttpServletResponse response
    ) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/sys/learning/content");
        return modelAndView;
    }

    @RequestMapping(value = "/query")
    @ResponseBody
    public Map<String,Object> query(HttpServletRequest req) {
        Map<String, Object> map = new HashMap<String, Object>();
        String pageIndexStr = req.getParameter("pageIndex");
        String type = req.getParameter("type");//1、职业能力知识；2、培训课件‘3、培训视频；4、示范教学片
        String title = req.getParameter("title");
       // String content = req.getParameter("content");
        String realName = req.getParameter("realname");//文件名称
        String currTitle = req.getParameter("currTitle");//所属课程的标题
        int pageIndex = 1;
        if (pageIndexStr != null && !"".equals(pageIndexStr)) {
            pageIndex = Integer.parseInt(pageIndexStr);
        }
        LearningContent learningContent = new LearningContent();
        //learningContent.setContent(content.getBytes());
        learningContent.setTitle(title);
        learningContent.setRealname(realName);
        learningContent.setCurrTitle(currTitle);
        if(type != null && !"".equals(type) && Tools.isNumber(type))
        {
            learningContent.setType(Integer.parseInt(type));
        }

        Page p = this.learningContentService.getList(learningContent, pageSize, pageIndex);

        map.put("pageCount",p.getTotalPageCount() );
        map.put("tableData",p.getResult());
        return map;
    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public Map<String,Object> delete(HttpServletRequest req) {
        String ids = req.getParameter("ids");
        int num = 0;
        if(ids != null && !"".equals(ids))
        {
            String[] idStrs = ids.split(",");
            if(idStrs.length>0)
            {
                for(String id : idStrs)
                {
                    if(Tools.isNumber(id))
                    {
                        num = num+this.learningContentService.delete(Integer.parseInt(id));
                    }
                }
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("num",num);
        return map;
    }


    /**
     * 增加
     * @return
     */
    @RequestMapping(value = "/add")
    public ModelAndView add() {
        ModelAndView modelAndView = new ModelAndView();
        List<Curriculum> curriculumList = this.curriculumService.getAll();
        modelAndView.addObject("curriculumList",curriculumList);
        modelAndView.setViewName("/sys/learning/content_add");
        return modelAndView;
    }

    /**
     * 增加数据
     * @return
     */
    @RequestMapping(value = "/addData")
    @ResponseBody
    public Map<String,Object> addData(

            HttpSession session,
            HttpServletRequest request,
            HttpServletResponse response) {
        String typeStr = request.getParameter("type");
        String title = request.getParameter("title");
        String timeStr = request.getParameter("time");
        String url = request.getParameter("url");
        String content = request.getParameter("content");
        String realname = request.getParameter("realname");

        LearningContent learningContent = new LearningContent();
        if(typeStr != null && !"".equals(typeStr) && Tools.isNumber(typeStr))
        {
            learningContent.setType(Integer.parseInt(typeStr));
        }
        else
        {
            learningContent.setType(1);//默认
        }
        learningContent.setTitle(title);
        if(timeStr != null && !"".equals(timeStr) && Tools.isNumber(timeStr))
        {
            learningContent.setTime(Integer.parseInt(timeStr));
        }
        else
        {
            learningContent.setTime(0);//默认
        }
        learningContent.setUrl(url);
        if(content != null)
        {
            learningContent.setContent(content.getBytes());
        }
        learningContent.setRealname(realname);
        String status="";
        int num=0;
        if ( session.getAttribute("sysUser") != null) {
            int uid = ((SysUser) session.getAttribute("sysUser")).getUid();
            learningContent.setCreatid(uid);
        }
        if(learningContent != null)
        {
            //把后缀提取 储存
            if(learningContent.getRealname() != null && learningContent.getUrl() != null)
            {
                String realName = learningContent.getRealname();
                String prefix=realName.substring(realName.lastIndexOf(".")+1);
                learningContent.setSpare1(prefix);
            }

            String time=Tools.getNowDate();
            learningContent.setCreattime(time);
            num=learningContentService.add(learningContent);

            //储存学习内容与课程的关系
            String[] currIdList = request.getParameterValues("currId");
            if(currIdList != null && currIdList.length > 0)
            {
                for(String currId:currIdList)
                {
                    if(Tools.isNumber(currId))
                    {
                        Curriculum2Content curriculum2Content = new Curriculum2Content();
                        curriculum2Content.setContentid(learningContent.getId());
                        curriculum2Content.setCurriculumid(Integer.parseInt(currId));
                        this.curriculum2contentService.add(curriculum2Content);
                    }
                }
            }
        }
        if(num>0){
            status="1";
        }else{
            status="0";
        }
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("status",status);
        return map;
    }

    /**
     * 编辑
     * @return
     */
    @RequestMapping(value = "/edit")
    public ModelAndView edit(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        String id=request.getParameter("id");
        String msg="";
        LearningContent learningContent=null;
        if(id != null && !"".equals(id) && Tools.isNumber(id)){
            int intId=Integer.parseInt(id);
            learningContent=learningContentService.getById(intId);
        }
        List<Curriculum> curriculumList = this.curriculumService.getAll();
        List<Curriculum> selectedCurrList = new ArrayList<Curriculum>();

        if(learningContent!=null){
            msg="获取成功";
            selectedCurrList = this.curriculumService.getByContentId(Integer.parseInt(id));
            for(Curriculum s:selectedCurrList)
            {
                for(Curriculum c:curriculumList)
                {
                    if(s.getId() == c.getId())
                    {
                        c.setIsSelected(1);
                        break;
                    }
                }
            }
        }else{
            msg="获取失败";
        }
        String content = "";
        if (learningContent.getContent() != null && learningContent.getContent().length > 0)
        {
            content = new String(learningContent.getContent());
        }
        modelAndView.addObject("content",content);
        modelAndView.addObject("curriculumList",curriculumList);
        modelAndView.addObject("obj",learningContent);
        modelAndView.setViewName("/sys/learning/content_edit");
        return modelAndView;
    }

    /**
     * 编辑
     * @return
     */
    @RequestMapping(value = "/editData")
    @ResponseBody
    public Map<String,Object> editData(
            HttpSession session,
            HttpServletRequest request,
            HttpServletResponse response) {
        String status="";
        int num= 0;
        String idStr = request.getParameter("id");
        if(idStr != null && !"".equals(idStr) && Tools.isNumber(idStr))
        {
            String typeStr = request.getParameter("type");
            String title = request.getParameter("title");
            String timeStr = request.getParameter("time");
            String url = request.getParameter("url");
            String content = request.getParameter("content");
            String realname = request.getParameter("realname");

            LearningContent learningContent = new LearningContent();
            learningContent.setId(Integer.parseInt(idStr));
            if(typeStr != null && !"".equals(typeStr) && Tools.isNumber(typeStr))
            {
                learningContent.setType(Integer.parseInt(typeStr));
            }
            else
            {
                learningContent.setType(1);//默认
            }
            learningContent.setTitle(title);
            if(timeStr != null && !"".equals(timeStr) && Tools.isNumber(timeStr))
            {
                learningContent.setTime(Integer.parseInt(timeStr));
            }
            else
            {
                learningContent.setTime(0);//默认
            }
            learningContent.setUrl(url);
            if(content != null)
            {
                learningContent.setContent(content.getBytes());
            }
            learningContent.setRealname(realname);
            if(learningContent != null) {
                //把后缀提取 储存
                if (learningContent.getRealname() != null && learningContent.getUrl() != null) {
                    String realName = learningContent.getRealname();
                    String prefix = realName.substring(realName.lastIndexOf(".") + 1);
                    learningContent.setSpare1(prefix);

                    //删除原保存的文件
                    LearningContent old = this.learningContentService.getById(learningContent.getId());
                    String oldUrl = old.getUrl();
                }
                num = learningContentService.edit(learningContent);

                //储存学习内容与课程的关系
                String[] currIdList = request.getParameterValues("currId");
                //首先删除全部原 关系数据
                this.curriculum2contentService.deleteAllByContentId(learningContent.getId());
                if(currIdList != null && currIdList.length > 0)
                {
                    for(String currId:currIdList)
                    {
                        if(Tools.isNumber(currId))
                        {
                            Curriculum2Content curriculum2Content = new Curriculum2Content();
                            curriculum2Content.setContentid(learningContent.getId());
                            curriculum2Content.setCurriculumid(Integer.parseInt(currId));
                            this.curriculum2contentService.add(curriculum2Content);
                        }
                    }
                }
            }
        }

        if(num>0){
            status="1";
        }else{
            status="0";
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status",status);

        return map;
    }
}
